package com.iscreen.dbupgrade;

import java.util.ArrayList;
import java.util.List;

import com.iscreen.dbupgrade.commands.CreateTableCommand;
import com.iscreen.dbupgrade.commands.InsertValuesCommand;
import com.iscreen.dbupgrade.objects.Command;
import com.iscreen.dbupgrade.objects.Plan;
import com.iscreen.dbupgrade.objects.Step;
import com.iscreen.dbupgrade.operations.UpgradeCommand;
import com.iscreen.dbupgrade.operations.UpgradeStep;
import com.iscreen.utils.db.connection.DBConnection;
import com.iscreen.utils.exceptions.IScreenException;
import com.iscreen.utils.xml.JAXBUtils;

public class UpgradePlan
{
	private DBConnection connection = DBUpgrade.getInstance().getConnection();

	private List<UpgradeStep> upgradeSteps = new ArrayList<UpgradeStep>();
	
	public void execute() throws IScreenException
	{
		createPlan();
		for (UpgradeStep step : upgradeSteps)
		{
			step.execute();
		}
	}

	private void createPlan() throws IScreenException
	{
		Plan plan = JAXBUtils.unmarshal(Plan.class, "D:/Applications/iScreen/src/iScreen-DBUpgrade/src/main/resources/upgrade.xml","D:/Applications/iScreen/src/iScreen-DBUpgrade/src/main/resources/upgrade.xsd");
		for (Step step : plan.getStep())
		{
			UpgradeStep upgradeStep = new UpgradeStep(connection, step);
			for (Command command : step.getCommands().getCommand())
			{
				UpgradeCommand upgradeCommand = createUpgradeCommand(upgradeStep, command);
				upgradeStep.addCommand(upgradeCommand);
			}
			upgradeSteps.add(upgradeStep);
		}
	}

	private UpgradeCommand createUpgradeCommand(UpgradeStep upgradeStep, Command command)
	{
		if (command.getCreateTable() != null)
		{
//			CreateTableQuery createTableQuery = queryFactory.createCreateTableQuery(command.getCreateTable());
			return new CreateTableCommand(command,upgradeStep);
		}
		else if (command.getInsertRows() != null)
		{
//			InsertValuesQuery inservValuesQuery = queryFactory.createInsertValuesQuery(command.getInsertRows());
			return new InsertValuesCommand(command, upgradeStep);
		}
		else
		{
			return null;
		}
	}
}

